﻿using System;
using Microsoft.Practices.ObjectBuilder2;

namespace UniAspect.UnityCommon.OptionalDependency
{
    public class OptionalDependencyResolver : IDependencyResolverPolicy
    {
        public readonly Type Type;
        public readonly string Name;

        public OptionalDependencyResolver(Type type, string name)
        {
            Type = type;
            Name = name;
        }

        public OptionalDependencyResolver(Type type)
                : this(type, null)
        {

        }

        public object Resolve(IBuilderContext context)
        {
            var newKey = new NamedTypeBuildKey(Type, Name);
            IBuilderContext contextForResolution = context.CloneForNewBuild(newKey, null);
            try
            {
                return contextForResolution.Strategies.ExecuteBuildUp(contextForResolution);
            }
            catch (BuildFailedException)
            {
                return null;
            }
        }
    }
}